import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { UrlConfigComponent } from './components/url-config/url-config.component';
const ignoreToken = ['login', 'logout', 'table'];

@Injectable()
export class CommonInterceptor implements HttpInterceptor {
  constructor(
    private httpClient: HttpClient,
    private urlConfig: UrlConfigComponent,
  ) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 先补全请求协议
    const url = req.url;
    const token = req.headers.get('token');
    // tslint:disable-next-line:no-console
    console.info('req url:' + url + 'req  header token:' + token);
    if (token === '' || token == null){
      this.httpClient.get(this.urlConfig.getTestUrl()).subscribe((response: any) => {
        console.log('need login!');
      });
    }
    const needToken = ignoreToken.filter(u => url.match(u));
    // 过滤掉不需要token的请求
    if (!needToken.length) {
      req = req.clone({
        url
      });
    } else {
      req = req.clone({
        url,
        headers: req.headers.set('token', 'asdqwe')
      });
    }
    return next.handle(req).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            console.log(event);
            if (event.status >= 500) {
              // 跳转错误页面
            }
          }
        },
        error => {
          // token过期 服务器错误等处理
        })
    );
  }
}
